<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>测试用例 - AI Worker</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
        }

        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            color: white;
        }

        .header h1 {
            font-size: 2em;
        }

        .btn-back {
            background: rgba(255,255,255,0.2);
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
        }

        .main-content {
            background: white;
            border-radius: 20px;
            padding: 40px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
        }

        .project-info {
            padding: 20px;
            background: #f8f9fa;
            border-radius: 10px;
            margin-bottom: 30px;
        }

        .project-title {
            font-size: 1.5em;
            color: #333;
            margin-bottom: 10px;
        }

        .toolbar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 20px;
            border-bottom: 2px solid #dee2e6;
        }

        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 8px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            margin-right: 10px;
        }

        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .btn-success {
            background: #28a745;
            color: white;
        }

        .btn-info {
            background: #17a2b8;
            color: white;
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.2);
        }

        .editor-container {
            border: 2px solid #dee2e6;
            border-radius: 10px;
            overflow: hidden;
        }

        #testCaseEditor {
            width: 100%;
            min-height: 500px;
            padding: 20px;
            border: none;
            font-family: 'Courier New', monospace;
            font-size: 14px;
            line-height: 1.6;
            resize: vertical;
        }

        #testCaseEditor:focus {
            outline: none;
        }

        .loading {
            display: none;
            text-align: center;
            padding: 40px;
        }

        .loading.show {
            display: block;
        }

        .spinner {
            border: 4px solid #f3f3f3;
            border-top: 4px solid #667eea;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto 10px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .message {
            padding: 15px;
            border-radius: 8px;
            margin-top: 20px;
            display: none;
        }

        .message.show {
            display: block;
        }

        .error {
            background: #f8d7da;
            color: #721c24;
        }

        .success {
            background: #d4edda;
            color: #155724;
        }

        .info {
            background: #d1ecf1;
            color: #0c5460;
        }

        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #666;
        }

        .empty-state-icon {
            font-size: 4em;
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>📝 测试用例</h1>
            <button class="btn-back" onclick="goBack()">← 返回项目列表</button>
        </div>

        <div class="main-content">
            <!-- 项目信息 -->
            <div class="project-info" id="projectInfo">
                <div class="loading show">
                    <div class="spinner"></div>
                    <p>加载项目信息...</p>
                </div>
            </div>

            <!-- 工具栏 -->
            <div class="toolbar">
                <div>
                    <button class="btn btn-success" onclick="saveTestCase()" id="saveBtn">
                        💾 保存
                    </button>
                    <button class="btn btn-info" onclick="exportTestCase()">
                        📥 导出
                    </button>
                    <button class="btn btn-primary" onclick="regenerateTestCase()" id="regenerateBtn">
                        🔄 重新生成
                    </button>
                </div>
                <div>
                    <button class="btn btn-info" onclick="goToAnalyze()">
                        🔍 执行代码分析
                    </button>
                </div>
            </div>

            <!-- 编辑器 -->
            <div class="editor-container" id="editorContainer">
                <div class="loading show">
                    <div class="spinner"></div>
                    <p>正在生成测试用例...</p>
                </div>
            </div>

            <!-- 消息提示 -->
            <div class="message error" id="errorMessage"></div>
            <div class="message success" id="successMessage"></div>
            <div class="message info" id="infoMessage"></div>
        </div>
    </div>

    <script>
        const projectId = window.location.pathname.split('/')[2];
        let currentTestCaseId = null;

        // 页面加载
        document.addEventListener('DOMContentLoaded', function() {
            loadProject();
            loadTestCase();
        });

        // 加载项目信息
        function loadProject() {
            fetch(`/api/projects/${projectId}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        renderProjectInfo(data.project);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                });
        }

        // 渲染项目信息
        function renderProjectInfo(project) {
            const container = document.getElementById('projectInfo');
            container.innerHTML = `
                <div class="project-title">${escapeHtml(project.name)}</div>
                ${project.description ? `<div>${escapeHtml(project.description)}</div>` : ''}
                <div style="margin-top:10px;color:#666;">
                    <span>🤖 ${project.ai_provider}</span>
                    <span style="margin-left:20px;">📅 ${new Date(project.created_at).toLocaleString('zh-CN')}</span>
                </div>
            `;
        }

        // 加载测试用例
        function loadTestCase() {
            fetch(`/api/projects/${projectId}/test-cases`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        if (data.test_cases && data.test_cases.length > 0) {
                            const testCase = data.test_cases[0]; // 获取最新的
                            currentTestCaseId = testCase.id;
                            renderEditor(testCase.content);
                        } else {
                            // 没有测试用例，显示空状态
                            showEmptyState();
                        }
                    } else {
                        showError(data.error || '加载失败');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showError('网络错误');
                });
        }

        // 渲染编辑器
        function renderEditor(content) {
            const container = document.getElementById('editorContainer');
            container.innerHTML = `
                <textarea id="testCaseEditor">${escapeHtml(content)}</textarea>
            `;
        }

        // 显示空状态
        function showEmptyState() {
            const container = document.getElementById('editorContainer');
            container.innerHTML = `
                <div class="empty-state">
                    <div class="empty-state-icon">📋</div>
                    <h2>还没有测试用例</h2>
                    <p>点击"重新生成"按钮创建测试用例</p>
                </div>
            `;
        }

        // 保存测试用例
        function saveTestCase() {
            const editor = document.getElementById('testCaseEditor');
            if (!editor) {
                showError('没有可保存的内容');
                return;
            }

            const content = editor.value;
            if (!content.trim()) {
                showError('测试用例内容不能为空');
                return;
            }

            const saveBtn = document.getElementById('saveBtn');
            saveBtn.disabled = true;
            saveBtn.textContent = '保存中...';

            const url = currentTestCaseId 
                ? `/api/test-cases/${currentTestCaseId}`
                : `/api/projects/${projectId}/test-cases`;
            
            const method = currentTestCaseId ? 'PUT' : 'POST';

            fetch(url, {
                method: method,
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({ content: content })
            })
            .then(response => response.json())
            .then(data => {
                saveBtn.disabled = false;
                saveBtn.textContent = '💾 保存';
                
                if (data.success) {
                    if (!currentTestCaseId) {
                        currentTestCaseId = data.test_case_id;
                    }
                    showSuccess('保存成功');
                } else {
                    showError(data.error || '保存失败');
                }
            })
            .catch(error => {
                saveBtn.disabled = false;
                saveBtn.textContent = '💾 保存';
                showError('网络错误: ' + error.message);
            });
        }

        // 导出测试用例
        function exportTestCase() {
            const editor = document.getElementById('testCaseEditor');
            if (!editor) {
                showError('没有可导出的内容');
                return;
            }

            const content = editor.value;
            const blob = new Blob([content], { type: 'text/plain' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `test_case_${projectId}_${Date.now()}.txt`;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
            
            showSuccess('导出成功');
        }

        // 重新生成测试用例
        function regenerateTestCase() {
            if (!confirm('重新生成将覆盖当前内容，是否继续？')) {
                return;
            }

            const regenerateBtn = document.getElementById('regenerateBtn');
            regenerateBtn.disabled = true;
            regenerateBtn.textContent = '生成中...';

            const container = document.getElementById('editorContainer');
            container.innerHTML = `
                <div class="loading show">
                    <div class="spinner"></div>
                    <p>正在生成测试用例，请稍候...</p>
                </div>
            `;

            fetch(`/api/projects/${projectId}/generate-test-case`, {
                method: 'POST'
            })
            .then(response => response.json())
            .then(data => {
                regenerateBtn.disabled = false;
                regenerateBtn.textContent = '🔄 重新生成';
                
                if (data.success) {
                    currentTestCaseId = data.test_case_id;
                    renderEditor(data.content);
                    showSuccess('生成成功');
                } else {
                    showError(data.error || '生成失败');
                    showEmptyState();
                }
            })
            .catch(error => {
                regenerateBtn.disabled = false;
                regenerateBtn.textContent = '🔄 重新生成';
                showError('网络错误: ' + error.message);
                showEmptyState();
            });
        }

        // 跳转到代码分析
        function goToAnalyze() {
            if (!currentTestCaseId) {
                showError('请先生成或保存测试用例');
                return;
            }
            window.location.href = `/project/${projectId}/analyze`;
        }

        // 返回
        function goBack() {
            window.location.href = '/';
        }

        // 显示消息
        function showMessage(type, message) {
            hideAllMessages();
            const messageDiv = document.getElementById(type + 'Message');
            messageDiv.textContent = message;
            messageDiv.classList.add('show');
            
            setTimeout(() => {
                messageDiv.classList.remove('show');
            }, 5000);
        }

        function showError(message) {
            showMessage('error', message);
        }

        function showSuccess(message) {
            showMessage('success', message);
        }

        function showInfo(message) {
            showMessage('info', message);
        }

        function hideAllMessages() {
            document.querySelectorAll('.message').forEach(msg => {
                msg.classList.remove('show');
            });
        }

        // HTML转义
        function escapeHtml(text) {
            if (!text) return '';
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }
    </script>
</body>
</html>

